package com.lepu.app.fun.my;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserLocaljsObject.BrowserLocaljsObjectDelegate;
import com.core.lib.utils.BrowserLocaljsObject;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.CustomWebView;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.bean.BeanCollectKnowledge;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

/**
 * @author wxd
 */
public class MyArticleInfoActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener, BrowserWebChromeDelegate,
        BrowserWebClientDelegate, AsyncRequest, BrowserLocaljsObjectDelegate {

    // sample request
    private static final String REQUEST_TEST = "request_test";

    private CustomWebView mWebView = null;
    private ProgressBar mProgressBar = null;

    private CustomTopBarNew mTopbar = null;
    private ImageView mCollectImageView;

    // 外边传入
    private String mTargetID = "";
    private String mArticleTag = "";
    private boolean mToolYqsp = false;//是否是孕期食谱的文章

    // 自己赋值
    private String mShareTitle = "";
    private String mShareUrl = "";
    private String mShareInfo = "";
    private String mShareCover = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_article_info_activity);

        init();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onResume() {
        mWebView.onResume();
        super.onResume();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mWebView != null) {
            try {
                mWebView.removeAllViews();
                mWebView.destroy();
                mWebView = null;

                LinearLayout contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
                contentLayout.removeView(mWebView);
            } catch (Exception e) {
                android.util.Log.d("错误 220 行", "webview Exception");
            }
        }
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
        closePage();
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    private void closePage() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();

            return;
        }

        finish(true);
    }

    /**
     * 初始化方法
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @SuppressLint({"SetJavaScriptEnabled", "NewApi"})
    private void init() {
        // topbar
        mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
        mTopbar.setTopbarTitle("");
        mTopbar.setTopbarLeftLayoutHide();
        mTopbar.setonTopbarNewLeftLayoutListener(this);
        //mTopbar.setTopbarLeftLayout(R.drawable.ship_webview_close, 0, 0);

        mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);

        mWebView = (CustomWebView) findViewById(R.id.webView);
        mWebView.setWebChromeClient(new BrowserWebChromeClient(this));
        mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setSaveEnabled(false);//让webview不保存状态，实际上对调用js没有用

        // js
        BrowserLocaljsObject jsObj = new BrowserLocaljsObject(this);
        mWebView.addJavascriptInterface(jsObj, "local_obj");

        mCollectImageView = (ImageView) findViewById(R.id.collectImageView);

        Bundle data = getIntent().getExtras();
        if (data != null && data.size() > 0) {

            if (data.containsKey("tool_yqsp")) {
                mToolYqsp = data.getBoolean("tool_yqsp");
            }

            if (data.containsKey("TargetID")) {
                mTargetID = data.getString("TargetID");
            }

            if(mToolYqsp)
            {
                mWebView.addJavascriptInterface(new YqspLocalObj(), "yqsp_obj");
            }

            if (data.containsKey("url")) {
                mShareUrl = data.getString("url");

                Utils.initWebViewSettings(mWebView, false);

                showWebViewUrl(mShareUrl);
            }

            if (data.containsKey("ArticleTag")) {
                mArticleTag = data.getString("ArticleTag");
                mTopbar.setTopbarTitle(mArticleTag);
            }
        }
    }

    public void showWebViewUrl(String url) {

        if (!StringUtilBase.stringIsEmpty(url)) {
            mWebView.loadUrl(url);
        }
    }

    public void viewClick(View view) {
        int rid = view.getId();
        switch (rid) {
            case R.id.collectImageView:

                clickCollect();
                break;

            case R.id.shareImageView:

                clickShare();
                break;
            case R.id.closeTextView:
                finish(true);
                break;
            case R.id.backImageView:
                closePage();
                break;

            default:
                break;
        }
    }

    private void updateCollectState() {

        boolean flag = BeanCollectKnowledge.checkCollectItemArticle(
                LoginUtil.getUserId(), mTargetID,
                BeanCollectKnowledge.TYPE_ARTICLE_NEW);
        if (flag) {
            mCollectImageView.setSelected(true);
        } else {
            mCollectImageView.setSelected(false);
        }
    }

    private void clickCollect() {

        AppEnterTongJi.clickEvent(47, mTargetID);

        boolean flagLogin = MainTabActivity.jumpLogin(this);

        if (flagLogin) {
            return;
        }

        String uid = LoginUtil.getUserId();
        boolean flag = BeanCollectKnowledge.checkCollectItemArticle(uid,
                mTargetID, BeanCollectKnowledge.TYPE_ARTICLE_NEW);

        boolean updateFlag = false;
        if (flag) {
            updateFlag = BeanCollectKnowledge.deleteItemArticle(uid,
                    mTargetID, BeanCollectKnowledge.TYPE_ARTICLE_NEW);

            UIHelper.showToast(this, R.string.collect_cancel);
        } else {
            BeanCollectKnowledge item = new BeanCollectKnowledge();
            item.Uid = uid;
            item.Time = System.currentTimeMillis();

            item.Type = BeanCollectKnowledge.TYPE_ARTICLE_NEW;
            item.Title = mShareTitle;
            if (TextUtils.isEmpty(mTargetID)) {
                //月子餐，没有文章id，收藏url
                item.SubTitle = mShareUrl;
            } else {
                //系列文章，需要标签
                item.SubTitle = mArticleTag;
            }

            item.ArticleID = mTargetID;
            updateFlag = BeanCollectKnowledge.insertCollectItem(item);

            UIHelper.showToast(this, R.string.collect_success);
        }

        if (updateFlag) {
            updateCollectState();
        }
    }

    private void clickShare() {

        AppEnterTongJi.clickEvent(48, mTargetID);

        String cover = "";

        if (TextUtils.isEmpty(mShareCover)) {
            cover = SdLocal.getAppIconPath(getApplicationContext());
        } else {
            cover = mShareCover;
        }

        String shareUrl = mShareUrl;

        if (!TextUtils.isEmpty(mTargetID)) {
            shareUrl = Setting.getShareArticleUrl(mTargetID);
        }

        // test
        // cover =
        // "http://img02.imgcdc.com/grab/img/20160522/22451463889854.jpg";

        // 调用官方sdk分享，可以各种形式
        ShareLib.Share(this, mShareTitle, mShareInfo, cover, shareUrl, false,
                new CallBack() {
                    @Override
                    public void callBackSuccess(Object obj) {
                        super.callBackSuccess(obj);

                        MyNetUtil.getInstance().requestShare(
                                MyArticleInfoActivity.this,
                                MyNetUtil.getInstance(), 1, mTargetID);
                    }
                });
    }

    class YqspLocalObj {

        @JavascriptInterface
        public void showYqspTitle(final String showtitle) {

            if(mWebView == null)
            {
                return;
            }

            if(TextUtils.isEmpty(showtitle))
            {
                return;
            }

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mTopbar.setTopbarTitle(showtitle);

                    LinearLayout rightMenuLayout = (LinearLayout) findViewById(R.id.rightMenuLayout);
                    if(showtitle.equals("孕期食谱"))
                    {
                        rightMenuLayout.setVisibility(View.GONE);
                        UserConfig.setConfig(MyArticleInfoActivity.this, Const.CONFIG_APP_TOOL_YQSP_ARTICLE_ID, mTargetID);
                    }else//if(title.equals("菜谱详情"))
                    {
                        if (!TextUtils.isEmpty(mTargetID)) {
                            rightMenuLayout.setVisibility(View.VISIBLE);
                            mCollectImageView.setVisibility(View.GONE);
                        } else {
                            rightMenuLayout.setVisibility(View.GONE);
                        }
                    }

                }
            });

        }
    }

    // =====================================
    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_TEST)) {

        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_TEST)) {
        }
    }

    // ===========================================================
    public void onProgressChanged(WebView view, int newProgress) {
        LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);

        mProgressBar.setMax(100);
        if (newProgress < 100) {
            if (mProgressBar.getVisibility() == View.GONE) {
                mProgressBar.setVisibility(View.VISIBLE);
            }
            mProgressBar.setProgress(newProgress);
        } else {
            mProgressBar.setProgress(100);

            Animation animation = AnimationUtils.loadAnimation(this,
                    R.anim.lib_broswer_progress);
            // 运行动画
            mProgressBar.startAnimation(animation);
            // 将 spinner 的可见性设置为不可见状态
            mProgressBar.setVisibility(View.GONE);
        }
    }

    // ======================================
    public void onPageStarted(String url) {
        LogUtilBase.LogD(null, "onPageStarted===>>" + url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>" + url);
        webView.loadUrl(url);
        return true;
    }

    public void onPageFinished(String url) {
        LogUtilBase.LogD(null, "onPageFinished===>>" + url);
        mShareUrl = url;

        if(mToolYqsp){
            //需要延时会儿执行，否则有些手机不起作用
            (new Handler()).postDelayed(new Runnable() {
                public void run() {
                    String getTitleJs = "javascript:window.yqsp_obj.showYqspTitle(document.getElementById('InfoForApp').getAttribute('showtitle'));";
                    mWebView.loadUrl(getTitleJs);
                }
            }, 500L);
        }
    }

    // ===============================================
    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getHtmlLength(int arg0) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getReferrer(String arg0) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getTitle(final String title) {

        if (!TextUtils.isEmpty(mShareUrl)) {
            mShareTitle = title;
        }

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getVideoSrc(String arg0) {

    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getCover(String cover) {
        if (!TextUtils.isEmpty(mShareUrl)) {
            mShareCover = cover;
        }
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getDescription(String Description) {
        if (!TextUtils.isEmpty(mShareUrl)) {
            mShareInfo = Description;
        }
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    public void getArticleID(String ArticleID) {

        if(mWebView == null)
        {
            return;
        }

        if (!TextUtils.isEmpty(mShareUrl)) {
            mTargetID = ArticleID;
        }

        if(!mToolYqsp)
        {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    LinearLayout rightMenuLayout = (LinearLayout) findViewById(R.id.rightMenuLayout);
                    if (!TextUtils.isEmpty(mTargetID)) {
                        rightMenuLayout.setVisibility(View.VISIBLE);
                        updateCollectState();
                    } else {
                        rightMenuLayout.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

}
